package cn.yusei.teamTribe.service.user;

import java.util.Date;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import cn.yusei.teamTribe.constant.ResponseCode;
import cn.yusei.teamTribe.dao.JedisDAO;
import cn.yusei.teamTribe.dao.user.UserAuthDAO;
import cn.yusei.teamTribe.dao.user.UserInfoDAO;
import cn.yusei.teamTribe.dao.user.po.UserAuthPO;
import cn.yusei.teamTribe.dao.user.po.UserInfoPO;
import cn.yusei.teamTribe.entity.Email;
import cn.yusei.teamTribe.entity.EmailAddress;
import cn.yusei.teamTribe.exception.SendEmailFailureException;
import cn.yusei.teamTribe.util.EmailUtil;
import cn.yusei.teamTribe.util.EncryptionUtil;
import cn.yusei.teamTribe.util.JedisKeyUtil;

@Service
public class EmailService implements InitializingBean{

	@Autowired
	private UserInfoDAO userInfoDAO;
	@Autowired
	private UserAuthDAO userAuthDAO;
	@Autowired
	private JedisDAO jedisDAO;
	
	@Value("${serverUrl}")
	private String serverUrl;
	@Value("${emailTryAginWaitSecond}")
	private int tryAginWaitSecond;
	@Value("${emailValidateSecond}")
	private int validateSecond;
	@Value("${active.title}")
	private String title;
	@Value("${active.content}")
	private String content;
	@Value("${emailAddress}")
	private String address;
	@Value("${emailPassword}")
	private String password;
	@Value("${emailNickName}")
	private String nickName;
	@Value("${emailContentType}")
	String contentType;
	@Value("${encoding}")
	private String encoding;
	
	
	private EmailAddress from;
	
	public void afterPropertiesSet() throws Exception {
		from = new EmailAddress(nickName, address);
	}
	
	public void sendEmail(String title, String content, EmailAddress... to)
	{
		Email email = new Email()
				.from(from)
				.to(to)
				.title(title)
				.content(content)
				.contentType(contentType)
				.encoding(encoding);
		try
		{
			EmailUtil.sendEmail(address, password, email);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			StringBuffer sb = new StringBuffer();
			sb.append("发送邮件至 ");
			sb.append('[');
			for(int i=0; i<to.length; i++)
			{
				sb.append(to[i].getAddress());
				if(i != to.length - 1)
					sb.append('，');
			}
			sb.append(']');
			sb.append("失败");
			throw new SendEmailFailureException(sb.toString());
		}
	}

	public int getAuthEmail(int id, String email, String authUrl)
	{
		UserInfoPO userInfoPO = userInfoDAO.select(id);
		UserAuthPO userAuthPO = userAuthDAO.selectById(id);
		if(userAuthPO == null)
			return ResponseCode.USER_NOT_EXISTS;
		if(userAuthPO.getEmail() != null)
			return ResponseCode.ALREADY_HAVE_EMAIL;
		if(jedisDAO.get(JedisKeyUtil.EMAIL_WAITING + id) != null)
			return ResponseCode.TRY_AGIN_WAITING;
		if(jedisDAO.get(JedisKeyUtil.EMAIL_USING + email) != null)
			return ResponseCode.EMAIL_IS_USING;
		if(userAuthDAO.selectEmail(email) != null)
			return ResponseCode.EMAIL_ALREADY_EXISTS;
		String uniqueString = EncryptionUtil.getEncryptedString(id + new Date().toString());
		String link = serverUrl + authUrl + uniqueString;
		jedisDAO.setex(JedisKeyUtil.EMAIL_WAITING + id, tryAginWaitSecond, "0");
		jedisDAO.setex(JedisKeyUtil.EMAIL_ID + uniqueString, validateSecond, String.valueOf(id));
		jedisDAO.setex(JedisKeyUtil.ID_EMAIL + id, validateSecond, email);
		jedisDAO.setex(JedisKeyUtil.EMAIL_USING + email, validateSecond, String.valueOf(id));
		String newContent =  content
				.replaceAll("\\{name\\}", userInfoPO.getNickname())
				.replaceAll("\\{link\\}", link);
		sendEmail(title, newContent, new EmailAddress(userInfoPO.getNickname(), email));
		return ResponseCode.REQUEST_SUCCESSED;
	}
	
	public int authEmail(String authUrl, String url)
	{
		String idString = jedisDAO.get(JedisKeyUtil.EMAIL_ID + url);
		String email = jedisDAO.get(JedisKeyUtil.ID_EMAIL + idString);
		if(idString == null || email == null)
			return ResponseCode.URL_INVALIDATE;
		int id = Integer.parseInt(idString);
		jedisDAO.del(JedisKeyUtil.EMAIL_ID + url);
		jedisDAO.del(JedisKeyUtil.ID_EMAIL + idString);
		jedisDAO.del(JedisKeyUtil.EMAIL_USING + email);
		UserAuthPO user = userAuthDAO.selectById(id);
		user.setEmail(email);
		userAuthDAO.update(user);
		return ResponseCode.REQUEST_SUCCESSED;
	}
	
}
